import 'package:flutter/foundation.dart';
import 'package:sqflite/sqflite.dart';
import '../models/song.dart';
import '../services/music_crawler_service.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';
import '../services/database_service.dart';
import '../services/download_manager.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class SongProvider with ChangeNotifier {
  Database? _db;
  bool _isUpdating = false;
  List<Song> _songs = [];

  bool get isUpdating => _isUpdating;
  List<Song> get songs => _songs;

  Future<void> initialize(Database db) async {
    _db = db;
    await updateSongs();
    await _loadSongs();
  }

  Future<void> _loadSongs() async {
    if (_db == null) return;

    final List<Map<String, dynamic>> maps =
        await _db!.query('songs', orderBy: 'createdAt DESC');
    _songs = maps.map((map) => Song.fromMap(map)).toList();
    notifyListeners();
  }

  Future<Song?> getById(String pk) async {
    if (_db == null) return null; // 如果数据库未初始化，则返回 null

    final List<Map<String, dynamic>> maps = await _db!.query(
      'songs',
      where: 'songId = ?',
      whereArgs: [pk],
    );

    // 使用 null 检查直接返回第一个元素，或返回 null
    return maps.isNotEmpty ? Song.fromMap(maps.first) : null;
  }

  Future<void> updateSongs() async {
    if (_db == null || _isUpdating) return;

    try {
      _isUpdating = true;
      notifyListeners();

      await MusicCrawlerService().crawlSongs();
    } catch (e) {
      print('更新歌曲失败: $e');
    } finally {
      _isUpdating = false;
      notifyListeners();
    }
  }

  Future<void> updateSongDownloadStatus(
    Song song,
    bool isDownloaded,
    String localPath,
    String lyrics,
  ) async {
    try {
      final updatedRows = await _db?.update(
        'songs',
        {
          'isDownloaded': isDownloaded ? 1 : 0,
          'localPath': localPath,
          'lyrics': lyrics,
        },
        where: 'songId = ?',
        whereArgs: [song.songId],
      );

      if (updatedRows == null || updatedRows == 0) {
        throw Exception('更新数据库失败: songId=${song.songId}');
      }

      // 确认更新成功后，重新加载数据
      await _loadSongs();
    } catch (e) {
      print('更新歌曲下载状态时出错: $e');
      rethrow;
    }
  }

  Future<void> createSong(Database db, String artist, String title) async {
    final songId = md5.convert(utf8.encode('${artist}_$title')).toString();
    try {
      final updatedRows = await _db?.insert('songs', {
        'songId': songId,
        'title': title,
        'artist': artist,
        'downloadUrl': "",
        'hot': 1,
        'isDownloaded': 0,
        'localPath': null,
        "createdAt": DateTime.now().toIso8601String()
      });

      if (updatedRows == null || updatedRows == 0) {
        throw Exception('更新数据库失败: songTitle=$title');
      }
      // 确认更新成功后，重新加载数据
      await _loadSongs();
    } catch (e) {
      print('更新歌曲下载状态时出错: $e');
      rethrow;
    }
  }

  Future<bool> downloadSong(Song song) async {
    try {
      // 设置下载状态
      await _db?.update(
        'songs',
        {'isDownloading': 1},
        where: 'songId = ?',
        whereArgs: [song.songId],
      );
      await _loadSongs(); // 刷新列表显示下载状态

      final database = await DatabaseService().database;
      final (localPath, lyrics) =
          await DownloadManager.downloadSongAndLyrics(song, database);

      if (localPath != null && lyrics != null) {
        await updateSongDownloadStatus(song, true, localPath, lyrics);
        // 重置下载状态
        await _db?.update(
          'songs',
          {'isDownloading': 0},
          where: 'songId = ?',
          whereArgs: [song.songId],
        );
        await _loadSongs();
        return true;
      }
      return false;
    } catch (e) {
      print('下载失败: $e');
      // 发生错误时也要重置下载状态
      await _db?.update(
        'songs',
        {'isDownloading': 0},
        where: 'songId = ?',
        whereArgs: [song.songId],
      );
      await _loadSongs();
      return false;
    }
  }

  Future<bool> exportSong(Song song) async {
    try {
      if (!song.isDownloaded || song.localPath == null) {
        return false;
      }

      final sourceFile = File(song.localPath!);
      if (!await sourceFile.exists()) {
        return false;
      }

      // 获取下载目录
      Directory? downloadsDir;
      // if (Platform.isMacOS) {
      //   final homeDir = Platform.environment['HOME'];
      //   if (homeDir != null) {
      //     downloadsDir = Directory('$homeDir/Downloads');
      //   }
      // } else {
      //   downloadsDir = await getDownloadsDirectory();
      // }
      downloadsDir = await getDownloadsDirectory();

      if (downloadsDir == null || !await downloadsDir.exists()) {
        return false;
      }

      // 创建目标文件名（去除非法字符）
      final safeArtist = song.artist.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
      final safeTitle = song.title.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
      final targetFile =
          File('${downloadsDir.path}/$safeArtist - $safeTitle.mp3');

      // 如果文件已存在，添加序号
      String finalPath = targetFile.path;
      int counter = 1;
      while (await File(finalPath).exists()) {
        finalPath =
            '${downloadsDir.path}/$safeArtist - $safeTitle ($counter).mp3';
        counter++;
      }

      // 复制文件
      await sourceFile.copy(finalPath);

      return true;
    } catch (e) {
      print('导出失败: $e');
      return false;
    }
  }

  Future<void> deleteSong(Song song) async {
    try {
      // 如果歌曲已下载，删除本地文件
      if (song.isDownloaded && song.localPath != null) {
        final file = File(song.localPath!);
        if (await file.exists()) {
          await file.delete();
        }
      }

      // 从数据库中删除
      final db = DatabaseService();
      await db.deleteSong(song.songId);

      // 从内存中删除
      _songs.removeWhere((s) => s.songId == song.songId);
      notifyListeners();
    } catch (e) {
      print('删除歌曲失败: $e');
      rethrow;
    }
  }

  Future<void> updateDownloadingStatus(Song song, bool isDownloading) async {
    try {
      await _db?.update(
        'songs',
        {'isDownloading': isDownloading ? 1 : 0},
        where: 'songId = ?',
        whereArgs: [song.songId],
      );
      await _loadSongs();
    } catch (e) {
      print('更新下载状态失败: $e');
      rethrow;
    }
  }

  // 添加一个公共方法来获取数据库
  Database? get database => _db;
}
